package com.lzt.admin.common.captcha.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lzt.admin.api.captcha.CaptchaAPI;
import com.lzt.admin.api.http.HttpHeaderAPI;
import com.lzt.admin.common.redis.config.RedisCore;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(CaptchaProperties.class)
public class CaptchaCore implements CaptchaAPI, HttpHeaderAPI {
    private final CaptchaProperties properties;
    private final RedisCore redisCore;
    public Map<String,Object> createCode(HttpServletRequest request, HttpServletResponse response, Map<String,Object> json) throws IOException {
        String uuid = IdUtil.simpleUUID();
        String verifyKey = StrUtil.join("", CAPTCHA_CODE_KEY, uuid);
        this.setHeader(response);
        SpecCaptcha specCaptcha = new SpecCaptcha(this.properties.getWidth(), this.properties.getHeight(), this.properties.getLen());
        redisCore.setCacheObject(verifyKey, specCaptcha.text(), CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        String img = specCaptcha.toBase64("");
        json.put(IMG,img);
        json.put(UUID,uuid);
        return json;
    }
    public void setHeader(HttpServletResponse response) {
        response.setDateHeader(HEADER_EXPIRES, HEADER_EXPIRES_VALUE);
        response.setHeader(HEADER_CACHE_CONTROL, HEADER_CACHE_CONTROL_NO_STORE);
        response.addHeader(HEADER_CACHE_CONTROL, HEADER_CACHE_CONTROL_CHECK);
        response.setHeader(HEADER_PRAGMA, HEADER_PRAGMA_NO_CACHE);
        response.setContentType(CONTENT_TYPE_JPEG);
    }
}
